package com.example.sources.servlet;

import com.example.sources.util.MapBean;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/9/20.
 */
public class PathVariableParam {

    public static boolean isPathVarible(String reqUrl, MapBean mapBean, MethodParamter methodParamter) {
        if (!mapBean.isPathVarivle()) {
            return false;
        } else {

        String regex ="";
        String[] x = mapBean.getPath().split("\\{");
            int i = 1;
            List<String> stringList = new ArrayList<>();
            for (String s1 : x) {

                if (s1.contains("}")){
                stringList.add(s1.substring(0,s1.lastIndexOf("}")));
                if (i == x.length){
                    regex+="([^/]*)"+s1.substring(s1.lastIndexOf("}")+1);
                }else {
                    regex+="(.*?)"+s1.substring(s1.lastIndexOf("}")+1);
                }
            }else {
                regex+=s1;
            }

            i++;
            }

            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(reqUrl);
                int size = stringList.size();
                while(m.find()){
                    for (int j = 0;j<size;j++){
                        methodParamter.putParameter(stringList.get(j), m.group(j+1));
                    }
                }
                return m.matches();
        }
    }

}
